package token

import (
	"github.com/dgrijalva/jwt-go"
	"pay/pkg/ecode"
)

func verifyExp(exp int64, now int64, required bool) bool {
	// 防止机器时间不同步，导致token突然过期，留出10分钟裕量
	if exp == 0 {
		return !required
	}
	return now-600 <= exp
}

func verifyIat(iat int64, now int64, required bool) bool {
	// 防止机器时间不同步，导致issue时间尚未抵达，留出10分钟裕量
	if iat == 0 {
		return !required
	}
	return now+600 >= iat
}

func VerifyJwt(exp, iat int64) error {
	vErr := new(jwt.ValidationError)
	// 默认的Claim类为秒，会导致token直接过期
	now := jwt.TimeFunc().Unix()
	if !verifyExp(exp, now, false) {
		vErr.Inner = ecode.Unauthenticated("登录已失效，请重新登录")
		vErr.Errors |= jwt.ValidationErrorExpired
	}
	if !verifyIat(iat, now, false) {
		vErr.Inner = ecode.Unauthenticated("登录已失效，请重新登录")
		vErr.Errors |= jwt.ValidationErrorIssuedAt
	}
	if vErr.Errors == 0 {
		return nil
	}
	return vErr
}
